package com.yinhai;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yinhai.tool.FileTools;
import com.yinhai.tool.UsualTools;

public class ShowImage extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ShowImage() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		FileTools ft=FileTools.getInstance();
		String fp=(String)request.getParameter("file");
		File f= new File(fp);
		this.showFileImage(request, response, ft, f);
	}
	
	public void showFileImage(HttpServletRequest request, HttpServletResponse response ,FileTools ft,File f){
		Image i = ft.getFileImage(f);//获取系统图标
		BufferedImage bi = new BufferedImage(16,16,BufferedImage.TYPE_4BYTE_ABGR);
		bi.createGraphics().drawImage(i, 0, 0, null);
		OutputStream os=null;
		try 
		{
			os = response.getOutputStream();
			ImageIO.write(bi,"PNG",os);
			os.close();
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		
		FileTools ft=FileTools.getInstance();
		
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));
//		String path=URLDecoder.decode(p,"utf-8");
//		String path=UsualTools.getInstance().changeCode(URLDecoder.decode(request.getParameter("file"),"utf-8"));
		
		File f= new File(path);
		this.showFileImage(request, response, ft, f);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
